



from db_interface import db_interface
from public_func.exchange_date import cal_stock_exchange_date
import requests
import random
from scipy.stats import percentileofscore



## 计算行业波动列表


def get_max_exchange_date(start="", end=""):
    if not start and not end:
        return ""
    sql = f"select * from (select max(date) as max_date from dongcai_ids_data where date<='{start}' union all " \
           f"select max(date) as max_date from dongcai_ids_data where date<='{end}') AS subquery "
    # print(sql)
    query = db_interface.stock_base.select(sql)
    res = [row[0].strftime("%Y-%m-%d") for row in query]
    return res


def get_idx_stock_count():
    sql = "select ids_name, count(*) from ids_stock_list where stock not " \
           "like '8%%' group by ids_name"
    query = db_interface.stock_base.select(sql)
    # for item in query:
    res = dict(query)

    return res


def get_industry_change():
    start_date, end_date = cal_stock_exchange_date(days=30)
    start, end = get_max_exchange_date(start_date, end_date)
    # print(start, end)
    sql = f"select name, code, date, `now`  from dongcai_ids_data " \
          f"where date between '{start}' and '{end}' order by `name`, `date` desc"
    # print(sql)
    query = db_interface.stock_base.select(sql)
    industry_dict= {}
    for item in query:
        name, code, date, now = item
        date = date.strftime("%Y-%m-%d")
        # print(item)
        if name not in industry_dict:
            industry_dict[name] = []
        industry_dict[name].append((name, code, date, now))

    res = []
    repeat_list = []
    ids_count = get_idx_stock_count()
    # print(ids_count)
    for k, v in industry_dict.items():
        # print(k, v)
        count = ids_count.get(k, "")
        unique_code = v[0][1]
        if unique_code not in repeat_list:
            repeat_list.append(unique_code)
            price_list = [x[-1] for x in v]
            change_pct = price_list[0] / price_list[-1] * 100 - 100
            percent = percentileofscore(price_list, price_list[0], kind='rank') ##
            res.append({
                "code": v[0][1],
                "name": k,
                "count": count,
                "price": price_list[0],
                "change_pct": round(change_pct, 2),
                "percent": round(percent, 2)
            })

    res = sorted(res, key=lambda x: x['change_pct'], reverse=True)
    # res = [{"id": i + 1, **item} for i, item in enumerate(res)]

    return res






def get_industry_plot(ids = "BK0459"):
    start_date, end_date = cal_stock_exchange_date(days=30)
    start, end = get_max_exchange_date(start_date, end_date)

    sql0 = f"select date, now from sh_days_data where date between '{start}' and '{end}'"
    query0 = db_interface.stock_base.select(sql0)
    sh_dict = dict([(x[0].strftime("%Y-%m-%d"), x[1]) for x in query0])

    sql = f"select name, code, date, `now`  from dongcai_ids_data " \
          f"where date between '{start}' and '{end}' and code = '{ids}' order by date asc"
    # print(sql)
    query = db_interface.stock_base.select(sql)
    res = {
        "date": [],
        "industry": [],
        "sh": [],
        "industry_name": ""
    }
    repeat_list = []
    for item in query:
        name, code, date, now = item
        # print(item)
        date = date.strftime("%Y-%m-%d")
        unique_code = f"{code}-{date}"
        if unique_code not in repeat_list:
            repeat_list.append(unique_code)
            res['date'].append(date)
            res['industry'].append(now)
            sh_price = sh_dict.get(date, "")
            res['sh'].append(sh_price)
            if not res['industry_name']:
                res["industry_name"]=name

    return res



if __name__ == "__main__":
    # d = get_max_exchange_date(date="2025-05-10")
    # print(d)
    r = get_industry_plot()
    print(r)




